package com.xltq.dao.impl;

import com.xltq.dao.IAddressDao;
import com.xltq.entity.Address;
import com.xltq.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

//实现dao层操作
public class IAddressDaoImpl implements IAddressDao {
    //提供DBUtils工具类的操作对象
    private QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
    @Override
    public List<Address> selectAddressByUid(int uid) throws Exception {
        //这里的地址排序的目的是为了保证 默认地址永远出现在地址栏中第一个位置
        //a_state的值 0不是默认地址 1是默认地址 所以降序排序
        String sql = "select a_id as aid, u_id as uid, a_name as aname, " +
                "a_phone as aphone, a_detail as adetail, " +
                "a_state as astate from address where u_id = ? order by a_state desc ;";
        return queryRunner.query(sql,new BeanListHandler<Address>(Address.class),uid);
    }

    @Override
    public void insertAddress(Address address) throws Exception {
         String sql = "insert into address(u_id, a_name, a_phone, a_detail, a_state)  values(?,?,?,?,?)";
         queryRunner.update(sql,address.getUid(),address.getAname(),address.getAphone(),
                 address.getAdetail(),address.getAstate());
    }

    @Override
    public void deleteAddress(String aid) throws Exception {
        String sql = "delete from address where a_id = ?";
        queryRunner.update(sql,aid);
    }

    @Override
    public void updateAddress(Address address) throws Exception {
        String sql = "update  address set a_state = ?,a_name = ?,a_phone = ?,a_detail = ? where a_id = ?";
        queryRunner.update(sql,address.getAstate(),address.getAname(),
                address.getAphone(),address.getAdetail(),address.getAid());
    }

    @Override
    public void updateAddressToDefault(String aid) throws Exception {
         String sql = "update address set a_state = 1 where a_id = ?";
         queryRunner.update(sql,aid);
    }

    @Override
    public void updateAddressToCommons(String aid, int uid) throws Exception {
        //除了a_id这个默认地址之外,剩余的用户地址皆为普通地址
        String sql = "update address set a_state = 0 where a_id != ? and u_id = ?";
        queryRunner.update(sql,aid,uid);

    }
}
